package com.redis.sdk;

import com.redis.sdk.cachecore.CacheProperties;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
@ConditionalOnProperty(prefix = "cache", name = "openLocalCache", havingValue = "true")
public class LocalCacheConfig {

    @Autowired
    private CacheProperties cacheProperties;

    @Bean
    public Cache<String, Object> caffeineCache() {
        Cache<String, Object> cache = Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(cacheProperties.getLocalCacheExpireTime(), TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(Integer.MAX_VALUE)
                .weakValues()
                .removalListener((String key, Object value, RemovalCause cause) ->  log.info("[监听]本地缓存移除，key：{}, 原因：{}", key, cause))
                .build();
        log.info("！！本地缓存配置开启！！");
        return cache;
    }
}
